using System;
using System.IO;
using System.Reflection;
using LuceneSearch.ContactApp.Entities;
using LuceneSearch.ContactApp.Indexing;
using NHibernate;
using StructureMap;

namespace LuceneSearch.ContactApp.Bootstrapping
{
    public class DataPop
    {
        private readonly ISessionFactory sessionFactory;

        public DataPop(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }

        public void PopulateSampleData()
        {
            var runningId = 0;

            var sampleDataStream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream(typeof(DataPop), "randomdata.csv");

            var reader = new StreamReader(sampleDataStream);

            reader.ReadLine(); //column headers

            using (var session = sessionFactory.OpenSession(ObjectFactory.GetInstance<NhIndexingInterceptor>()))
            using (var trans = session.BeginTransaction())
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();

                    var lineValues = line.Split('|');

                    var customer = new Contact();

                    customer.Id = runningId++;
                    customer.FirstName = lineValues[0];
                    customer.LastName = lineValues[1];
                    customer.Email = lineValues[2];
                    customer.Address = lineValues[3];
                    customer.City = lineValues[4];
                    customer.Zip = lineValues[5];
                    customer.State = lineValues[6];
                    customer.Country = lineValues[7];
                    customer.Notes = lineValues[8];
                    customer.Colors = lineValues[9];

                    session.Save(customer);
                }
                
                trans.Commit();
            }
        }
    }
}